<template>
  <div class="category-list-container">
    <el-card class="card-container" style="height: 100%;">
      <!-- 按钮区域 -->
      <div class="table-header">
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button type="danger" @click="handleDeleteSelected">批量删除</el-button>
      </div>

      <!-- 表格 -->
      <el-table :data="categoryList" stripe style="width: 100%;" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="ID" width="60" align="center" />
        <el-table-column prop="name" label="分类名称" min-width="180" />
        <el-table-column prop="createUser" label="创建人" min-width="120" align="center" />
        <el-table-column label="创建时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateUser" label="更新人" min-width="120" align="center" />
        <el-table-column label="更新时间" min-width="180" align="center">
          <template #default="{ row }">
            {{ formatDate(row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="120" align="center">
          <template #default="{ row }">
            <el-button size="small" type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          layout="prev, pager, next"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>

    <!-- 新增分类对话框 -->
    <el-dialog title="新增分类" v-model="addDialogVisible" width="30%">
      <el-form :model="newCategory" label-width="100px">
        <el-form-item label="分类名称">
          <el-input v-model="newCategory.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddCategory">确认</el-button>
      </template>
    </el-dialog>

    <!-- 编辑分类对话框 -->
    <el-dialog title="编辑分类" v-model="editDialogVisible" width="30%">
      <el-form :model="editCategory" label-width="100px">
        <el-form-item label="分类名称">
          <el-input v-model="editCategory.name" autocomplete="off" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitEditCategory">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import controller from '@/api/controller'

export default {
  name: 'ProductCategoryView',
  data() {
    return {
      categoryList: [],
      total: 0,
      currentPage: 1,
      pageSize: 10,
      selectedRows: [],

      addDialogVisible: false,
      newCategory: {
        name: ''
      },

      editDialogVisible: false,
      editCategory: {
        id: null,
        name: ''
      }
    }
  },
  methods: {
    async getCategoryListPage(page = 1) {
      try {
        const res = await controller.getCategoryListPage(page, this.pageSize)
        if (res && res.code === 200 && res.data) {
          this.categoryList = res.data.records.map(item => ({
            id: item.cId,
            name: item.cName,
            createTime: item.cCreateTime,
            updateTime: item.cUpdateTime,
            createUser: item.cCreateUser || '-',
            updateUser: item.cUpdateUser || '-'
          }))
          this.total = res.data.total
          this.currentPage = page
        } else {
          this.$message.error('获取分类列表失败')
        }
      } catch (error) {
        console.error('请求失败:', error)
        this.$message.error('请求失败，请检查网络')
      }
    },
    handlePageChange(page) {
      this.currentPage = page
      this.getCategoryListPage(page)
    },
    handleEdit(row) {
      this.editCategory.id = row.id
      this.editCategory.name = row.name
      this.editDialogVisible = true
    },
    async handleDelete(row) {
      this.$confirm(`确定要删除分类：${row.name}？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await controller.deleteCategoryByIds([row.id])
          this.$message.success('删除成功')
          this.getCategoryListPage(this.currentPage)
        } catch (error) {
          this.$message.error('删除失败')
          console.error('删除分类失败:', error)
        }
      }).catch(() => {})
    },
    async handleDeleteSelected() {
      if (this.selectedRows.length === 0) {
        this.$message.warning('请先选择要删除的数据')
        return
      }

      const names = this.selectedRows.map(r => r.name).join('、')
      const ids = this.selectedRows.map(r => r.id)

      this.$confirm(`确定要删除选中的 ${this.selectedRows.length} 条数据？【${names}】`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await controller.deleteCategoryByIds(ids)
          this.$message.success(`已删除 ${this.selectedRows.length} 条数据`)
          this.getCategoryListPage(this.currentPage)
        } catch (error) {
          this.$message.error('删除失败')
          console.error('批量删除失败:', error)
        }
      }).catch(() => {})
    },
    handleSelectionChange(rows) {
      this.selectedRows = rows
    },
    handleAdd() {
      this.newCategory.name = ''
      this.addDialogVisible = true
    },
    async submitAddCategory() {
      if (!this.newCategory.name.trim()) {
        this.$message.warning('分类名称不能为空')
        return
      }

      const now = new Date()
      const username = this.$store.getters.getUserInfo?.username || '未知用户'

      try {
        await controller.addCategory({
          cName: this.newCategory.name,
          cCreateTime: now,
          cUpdateTime: now,
          cCreateUser: username,
          cUpdateUser: username
        })

        this.$message.success('新增分类成功')
        this.addDialogVisible = false
        this.getCategoryListPage(this.currentPage)
      } catch (error) {
        console.error('新增分类失败:', error)
        this.$message.error('新增失败，请重试')
      }
    },
    async submitEditCategory() {
      if (!this.editCategory.name.trim()) {
        this.$message.warning('分类名称不能为空')
        return
      }

      const username = this.$store.getters.getUserInfo?.username || '未知用户'
      const now = new Date()

      try {
        await controller.updateCategory({
          cId: this.editCategory.id,
          cName: this.editCategory.name,
          cUpdateTime: now,
          cUpdateUser: username
        })

        this.$message.success('更新分类成功')
        this.editDialogVisible = false
        this.getCategoryListPage(this.currentPage)
      } catch (error) {
        console.error('更新分类失败:', error)
        this.$message.error('更新失败，请重试')
      }
    },
    formatDate(time) {
      if (!time) return ''
      const date = new Date(time)
      return date.toISOString().replace('T', ' ').substring(0, 19)
    }
  },
  mounted() {
    const userInfo = this.$store.getters.getUserInfo
    if (userInfo && userInfo.username) {
      console.log('当前用户名:', userInfo.username)
    } else {
      console.log('未找到登录信息')
    }

    this.getCategoryListPage()
  }
}
</script>

<style scoped>
.category-list-container {
  display: flex;
  justify-content: center;
  width: 100%;
  padding: 20px;
}

.card-container {
  width: 100%;
  box-sizing: border-box;
}

.table-header {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.el-table .cell {
  white-space: nowrap;
}
</style>